package com.dys.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @className: com.dys.servlet.ServletCookie2
 * @description: Cookie记录访问次数
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/09/20 21:11
 */
@WebServlet(urlPatterns = "/servlet03.do")
public class ServletCookie3 extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行ServletCookie3中的方法......");
        boolean flag = false;
        // 读取请求中的Cookie
        Cookie[] cookies = req.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if (cookieName.equals("servletCookie3")) {
                    // 创建Cookie次数+1
                    int count = Integer.parseInt(cookie.getValue()) + 1;
                    Cookie c1 = new Cookie("servletCookie3", String.valueOf(count));
                    resp.addCookie(c1);
                    resp.setContentType("text/html;charset=utf-8");
                    resp.getWriter().println("欢迎您第" + count + "次回来！");
                    System.out.println("欢迎您第" + count + "次回来！");
                    flag = true;
                }
            }
        }
        if (!flag) {
            System.out.println("您好，欢迎您第1次访问！");
            Cookie c1 = new Cookie("servletCookie3", "1");
            resp.addCookie(c1);
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().println("您好，欢迎您第1次访问！");
        }
    }
}
